import { Component, OnInit } from '@angular/core';
import { PopoverController } from '@ionic/angular';
import { PopoverComponent } from '../popover/popover.component';
import { Storage } from '@ionic/storage';
import { ToastController } from '@ionic/angular';
import { Router } from '@angular/router';
import { TokenAuthServiceProxy, AuthenticateModel } from '../../shared/service-proxies/service-proxies';
import { userInfo } from 'os';
import { AppConsts } from '../../shared/AppConsts';
import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';


@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
  providers: [TokenAuthServiceProxy]
})
export class LoginPage implements OnInit {

  userName: string;
  userPwd: string;
  showPwd: boolean;
  captchaCodeImg: string;
  codeNumber: string;
  userStorage: any;
  loginParam: AuthenticateModel = new AuthenticateModel;

  constructor(
    private screenOrientation: ScreenOrientation,
    public popoverController: PopoverController,
    public toastCtrl: ToastController,
    public userServe: TokenAuthServiceProxy,
    private storage: Storage,
    public router: Router
  ) {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  }

  passNum: number = 0;
  passType: string;

  ngOnInit() {
    // this.isLogin();
  }

  ionViewWillEnter() {
    this.screenOrientation.lock(this.screenOrientation.ORIENTATIONS.PORTRAIT);
  }

  async toastTip(message: string) {
    let toast = await this.toastCtrl.create({
      message: message,
      duration: 2000,
      position: 'middle'
    });
    toast.present();
  }

  // isLogin() {
  //   this.storage.get('accessToken').then((res) => {
  //     console.log("登录res",res)
  //     if (!!res) {
  //       // this.router.navigateByUrl('/home');
  //       AppConsts.sessonToken = res.accessToken;
  //     }
  //   })
  // }

  logIn() {
    if (!this.userName) {
      this.toastTip('请填写用户名');
      return;
    }
    if (!this.userPwd) {
      this.toastTip('请填写密码');
      return;
    }
    this.loginParam.userNameOrEmailAddress = this.userName;
    this.loginParam.password = this.userPwd;
    
    this.userServe.authenticate(this.loginParam)
      .subscribe((res) => {
          this.storage.set("accessToken", res.accessToken);
          AppConsts.sessonToken = res.accessToken;
          // console.log("AppConsts.sessonToken", AppConsts.sessonToken)
          this.storage.set(this.userName, this.userName);
          this.storage.get(this.userName).then((val) => {
            this.userStorage = val;
            this.router.navigate(['/home']);
          });
      })
  }

}
